package com.carlinfo.back.servlet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.common.servlet.BaseServlet;
import com.carlinfo.common.util.ConstantFinalUtil;
import com.carlinfo.userscenter.users.pojo.AAdmins;
import com.carlinfo.userscenter.users.service.IUserService;
import com.carlinfo.userscenter.users.service.impl.UserServiceImpl;

public class AdminsBackServlet extends BaseServlet
{

	private IUserService usersService = new UserServiceImpl();

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String param = request.getParameter("method");
		logger.info("==method:{}==", request.getParameter("method"));
		if ("main".equalsIgnoreCase(param))
		{
			this.main(request, response);
		} else if ("welcome".equalsIgnoreCase(param))
		{
			this.welcome(request, response);
		} else if ("adminsUpdate".equalsIgnoreCase(param))
		{
			this.adminsUpdate(request, response);
		} else if ("adminsUpdateSubmit".equalsIgnoreCase(param))
		{
			this.adminsUpdateSubmit(request, response);
		}else if ("userMain".equalsIgnoreCase(param))
		{
			this.userMain(request, response);
		}
	}

	private void userMain(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
//		System.out.println("我是新鲜的");
		String path = "/WEB-INF/jsp/back/user/main.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void adminsUpdateSubmit(HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException
	{
		/* 判断是不是二进制流的方式提交 */
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		String id = request.getParameter("id");
		if (isMultipart)
		{
			Map<String, List<Object>> resultMap = this.proccedFileUpload(request);

			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", id);
			AAdmins admins = this.usersService.findOneAdminsService(condMap);
			String email = resultMap.get("email").get(0) + "";
			String trueName = resultMap.get("trueName").get(0) + "";
			String sex = resultMap.get("sex").get(0) + "";
			String status = resultMap.get("status").get(0) + "";
			String phone = resultMap.get("phone").get(0) + "";
			String qq = resultMap.get("qq").get(0) + "";
			List<Object> fileList = resultMap.get("file");

			String truePath = ConstantFinalUtil.IMG_JSON.getString("truePath");
			String relativePath = ConstantFinalUtil.IMG_JSON.getString("relativePath") + "admins/"
					+ this.dateUtil.dateToStr(new Date()) + "/" + fileList.get(1);
			File tarFile = new File(truePath + relativePath);

			if (!tarFile.getParentFile().exists())
			{
				tarFile.getParentFile().mkdirs();
			}

			InputStream is = (InputStream) fileList.get(2);
			OutputStream os = new FileOutputStream(tarFile);
			this.fileUtil.copy(is, os);

			if (admins != null)
			{
				try
				{
					admins.setPhotoPath(relativePath);
					admins.setEmail(email);
					admins.setQq(qq);
					admins.setPhone(phone);
					admins.setTrueName(trueName);
					admins.setSex(Byte.valueOf(sex));
					admins.setStatus(Byte.valueOf(status));
					JSONObject jsonObject = this.usersService.updateOneAdminsService(admins);
					response.setCharacterEncoding("UTF-8");
					PrintWriter writer = response.getWriter();
					writer.println(jsonObject);
					writer.flush();
					writer.close();
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}

	}

	private Map<String, List<Object>> proccedFileUpload(HttpServletRequest request)
	{

		Map<String, List<Object>> resultMap = new HashMap<String, List<Object>>();

		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = this.getServletConfig().getServletContext();
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		// 创建一个上传文件的解析器
		ServletFileUpload upload = new ServletFileUpload(factory);

		try
		{
			/* 解析request */
			List<FileItem> items = upload.parseRequest(request);
			for (Iterator iterator = items.iterator(); iterator.hasNext();)
			{
				FileItem fileItem = (FileItem) iterator.next();
				if (fileItem.isFormField())
				{
					String name = fileItem.getFieldName();
					String value = fileItem.getString();
					List<Object> resultList = new ArrayList<Object>();
					resultList.add(value);
					resultMap.put(name, resultList);
				} else
				{
					/* 上传的字段名 */
					String name = fileItem.getFieldName();
					/* 上传的文件名字 */
					String fileName = fileItem.getName();
					/* 文件的mime类型 */
					String contentType = fileItem.getContentType();
					/*
					 * File file = new File("d:/test", fileName); fileItem.write(file);
					 */
					List<Object> resultList = new ArrayList<Object>();
					/* 字段名 */
					resultList.add(name);
					/* 文件名 */
					resultList.add(fileName);
					/* 输入流 */
					resultList.add(fileItem.getInputStream());
					resultMap.put(name, resultList);
				}
			}
		} catch (FileUploadException e1)
		{
			e1.printStackTrace();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return resultMap;
	}

	private void adminsUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", admins.getId());
		admins = this.usersService.findOneAdminsService(condMap);

		request.setAttribute("admins", admins);
		String path = "/WEB-INF/jsp/back/admins/adminsUpdate.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void welcome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/admins/welcome.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/admins/main.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}
}
